const { course } = require('../models')

module.exports =  {
  /**
   * 新增一个课程
   * @return 成功时返回新增的课程，失败时返回失败信息
   */
  async addCourse(ctx, next) {
    try {
        let result = await course.create(ctx.request.body);
        return ctx.body = { status: 'ok', data: result };
    } catch (e) {
        return ctx.body = { status: 'fail', data: e.message };
    }
  },
  /**
   * 分页获取课程
   * @return 成功时返回分页的课程，失败时返回失败信息
   */
  async getCourseByPage (ctx, next) {
    try {
      let pageNum = parseInt(ctx.query.pageNum), pageSize = parseInt(ctx.query.pageSize)
      let lists = await course.find(null, null, { skip: (pageNum - 1) * pageSize, limit: pageSize }).sort({create_time: 'desc'}).populate('students')
      let total = await course.count();
      return ctx.body = { status: 'ok', data: {lists, total} };
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  },

  /**
   * 新增一个学生
   * @return 成功时返回更改后课程，失败时返回失败信息
   */
  async addStudent(ctx, next) {
    try {
      let result = await course.findById(ctx.request.body.cid)
      if(result.students.indexOf(ctx.request.body.sid) > -1) {
        return ctx.body = { status: 'fail', data: '你已经签到过了' };
      }
      result.students.push(ctx.request.body.sid)
      result = await result.save({students: result})
      return ctx.body = { status: 'ok', data: result };
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  }

}